import React, { Component } from 'react'
import { reqcartadd, reqgetgoodsinfo } from '../../http/api';
import "./detail.less"
import qs from 'qs';
import Header from '../../components/header/header';
import { MyContext } from '../../App';
import { Toast } from 'antd-mobile';

export default class detail extends Component {
  constructor() {
    super();
    this.state = {
      info: [],
      isshow: false,
      num:1,
    }
  }
  UNSAFE_componentWillMount() {
    let id = qs.parse(this.props.match.params.id)
    reqgetgoodsinfo({ id: id.id }).then(res => {
      if (res.data.code == 200) {
        this.setState({
          info: res.data.list
        })
      }
    })
  }
  //数量增加
  numjia(){
    this.setState({
      num:this.state.num+1,
    })
  }
  //数量减少
  numjian(){
    if(this.state.num==1){
      Toast.show({
        icon:"success",
        content:"不能再少了"
      })
      return
    }
    this.setState({
      num:this.state.num-1
    })
  }
  //加入购物车
  reqinfo(){
    //获取参数
    let uid = JSON.parse(sessionStorage.getItem("info")).uid
    let type = Number((this.props.match.params.id).split("&")[1].split("=")[1])
    let goodsid = Number((this.props.match.params.id).split("&")[0].split("=")[1])
    let num = this.state.num
    reqcartadd({uid,type,goodsid,num}).then(res=>{
      if(res.data.code==200){
        Toast.show({
          icon:"success",
          content:res.data.msg
        })
        this.setState({isshow:false})
      }
    })
  }
  render() {
    let { info, isshow,num } = this.state
    return (
      <div className='detail'>
        <Header text="商品详情" back></Header>
        <div className='con'>
          {info.map((item) => {
            return (
              <MyContext.Consumer key={item.id}>
                {({ $pre }) => {
                  return (
                    <>
                      <div>
                        <img src={$pre + item.img} alt="" />
                        <p>价格：{item.price} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;原价:{item.market_price}</p>
                        <p>{item.description}</p>
                        <p>{item.goodsname}</p>
                      </div>
                    </>
                  )
                }}
              </MyContext.Consumer>
            )
          })}
          <div className='button'>
            <button onClick={() => this.setState({ isshow: !isshow })}>加入购物车</button>
          </div>
        </div>
        {isshow ? (
          <div className='mengban' onClick={(e)=>e.target.className=="mengban"?this.setState({isshow:false}):null}>
            <div>
              <span onClick={()=>this.setState({isshow:false})}>X</span>
              <p>数量：</p>
              <p><button onClick={()=>this.numjian()}>-</button><span>{num}</span><button onClick={()=>{this.numjia()}}>+</button></p>
              <button onClick={()=>this.reqinfo()}>加入购物车</button>
            </div>
          </div>
        ) : null}
      </div>
    )
  }
}
